package com.force.module.webserver.exception;

import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

@ControllerAdvice
public class GlobalExceptionHandler {

	@ExceptionHandler(value = {RuntimeException.class,Exception.class})
	public ModelAndView handleRuntimeException(Exception e, HttpServletRequest request, HttpServletResponse response) {
		Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
		ModelAndView modelAndView=new ModelAndView();
		String title = "错误";
		String errorCode = "未知错误";
		String errorMsg = "出错了";
		String errorDesc = "抱歉，服务器遇到了问题，请稍后再试。";

		if (status != null) {
			int statusCode = Integer.parseInt(status.toString());

			if (statusCode == 404) {
				title = "404 - 页面未找到";
				errorCode = "404";
				errorMsg = "页面未找到";
				errorDesc = "您访问的页面不存在或已被移除。";
			} else if (statusCode == 500) {
				title = "500 - 内部服务器错误";
				errorCode = "500";
				errorMsg = "内部服务器错误";
				errorDesc = "服务器发生异常，请联系管理员。";
			}
		}
		modelAndView.setViewName("error");

		modelAndView.addObject("title", title);
		modelAndView.addObject("errorCode", errorCode);
		modelAndView.addObject("errorMsg", errorMsg);
		modelAndView.addObject("errorDesc", e.getClass().getTypeName());

		return modelAndView; // 对应 templates/error.html
	}

}
